<template>
  <div class="experimentalist_wrap">
    <div class="experimentalist_top_box">
      <el-card class="experimentalist_top_card">
        <el-form :inline="true" class="demo-form-inline">
          <!-- 用户名 -->
          <el-form-item label="用户名">
            <el-input v-model="queryParamData.account" placeholder="请输入用户名" clearable style="width: 150px" />
          </el-form-item>

          <!-- 姓名 -->
          <el-form-item label="姓名">
            <el-input v-model="queryParamData.name" placeholder="请输入姓名" style="width: 150px" clearable />
          </el-form-item>

          <!-- 是否管理员 -->
          <el-form-item label="是否管理员">
            <el-select v-model="queryParamData.isManager" filterable placeholder="请选择" style="width: 120px" clearable>
              <el-option label="是" value="y"> </el-option>
              <el-option label="否" value="n"> </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="querySelectClick">
              <el-icon style="margin-right: 6px"><Search /></el-icon>
              查询
            </el-button>

            <el-button type="primary" @click="addEditClick(0, null)">
              <el-icon style="margin-right: 6px"><Plus /></el-icon>
              添加
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="experimentalist_bottom_box">
      <el-card class="experimentalist_bottom_card">
        <el-table :data="byPageTableData" border style="width: 100%" stripe v-loading="isLoading">
          <el-table-column prop="serialNumber" label="序号" width="80" align="center" />
          <el-table-column prop="account" label="用户名" align="center" />
          <el-table-column prop="name" label="姓名" align="center" />
          <el-table-column prop="isManager" label="是否管理员" align="center" />
          <el-table-column prop="creator" label="创建人" align="center" />

          <!-- 操作 -->
          <el-table-column label="操作" align="center" width="200">
            <template #default="scoped">
              <div class="operation_box">
                <!-- 编辑 -->
                <span class="edit_text" @click="addEditClick(1, scoped.row)">编辑</span>

                <!-- 重置密码 -->
                <el-popconfirm width="240" title="确定重置此实验员的密码吗?" @confirm="resetPswConfirmClick(scoped.row)">
                  <template #reference>
                    <span class="edit_text">重置密码</span>
                  </template>
                </el-popconfirm>

                <!-- 删除 -->
                <el-popconfirm width="200" title="确定删除此实验员吗?" @confirm="delLabUserConfirmClick(scoped.row)">
                  <template #reference>
                    <span class="del_text">删除</span>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination_box">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :current-page="queryParamData.page"
            :page-size="queryParamData.size"
            @current-change="pageChange"
            @size-change="sizeChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 添加编辑表单弹窗 -->
    <el-dialog v-model="isShowAddEditDialog" :title="`${isFormAdd ? '添加' : '编辑'}实验员`" top="6vh" width="500" draggable>
      <!-- 步骤条 -->
      <div class="processBox">
        <a-steps :current="currentAddEditStep" :items="stepsList"></a-steps>
      </div>

      <!-- 树形组件 -->
      <div class="add_edit_tree_box" v-if="currentAddEditStep != 0">
        <el-tree
          :data="dataSource"
          class="lab_tree"
          node-key="id"
          default-expand-all
          ref="addEditExpLabTreeRef"
          :expand-on-click-node="false"
          :check-on-click-node="true"
          show-checkbox
          :default-checked-keys="addEditLabIdList"
          @node-contextmenu="
            (e, a) => {
              rightClick(e, a);
            }
          "
          :highlight-current="true"
          @check="addEditTreeCheckChange"
          :current-node-key="addEditCurrentNodeKey"
        >
        </el-tree>
      </div>
      <div class="is_m_box" v-if="currentAddEditStep != 0">
        <span class="label">设置为管理员</span>
        <el-radio-group v-model="addEditFormData.isManager">
          <el-radio value="y" size="large"> 是</el-radio>
          <el-radio value="n" size="large">否</el-radio>
        </el-radio-group>
      </div>

      <!-- 实验员信息表单 -->
      <div
        :class="{
          add_edit_form_box: true,
          hids: currentAddEditStep != 0
        }"
      >
        <el-form
          :model="addEditFormData"
          label-position="right"
          label-width="100px"
          ref="addEditFormRef"
          :rules="addEditFormRule"
        >
          <!-- 用户名 -->
          <el-form-item label="用户名" prop="account">
            <el-input placeholder="请输入用户名" v-model="addEditFormData.account" />
          </el-form-item>

          <!-- 姓名 -->
          <el-form-item label="姓名" prop="name" style="margin-top: 24px">
            <el-input placeholder="请输入姓名" v-model="addEditFormData.name" />
          </el-form-item>

          <!-- 密码 -->
          <!-- <el-form-item label="密码" prop="psw">
            <el-input placeholder="请输入密码" type="password" v-model="addEditFormData.psw" />
          </el-form-item> -->

          <!-- 年龄 -->
          <el-form-item label="年龄" prop="age" style="margin-top: 24px">
            <el-input placeholder="请输入年龄" v-model="addEditFormData.age" />
          </el-form-item>

          <!-- 邮箱 -->
          <el-form-item label="邮箱" prop="email" style="margin-top: 24px">
            <el-input placeholder="请输入邮箱" v-model="addEditFormData.email" />
          </el-form-item>

          <!-- 密码注释 -->
          <div class="pws_zs">
            <span class="label">注意：</span>
            <span class="pws_zs_text">添加的实验员默认密码为：123456</span>
          </div>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addEditDialogCancelClick">取消</el-button>
          <el-button v-if="currentAddEditStep == 1" type="primary" @click="addEditDialogBackStepClick">上一步</el-button>
          <el-button type="primary" @click="addEditDialogConfirmClick(addEditFormRef)">
            {{ currentAddEditStep == 0 ? "下一步" : "确定" }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from "vue";
export default defineComponent({
  name: "Experimentalist"
});
</script>
<script lang="ts" setup>
import {
  selectExperimentalistListApi,
  addLabUserApi,
  editLabUserApi,
  delLabUserApi,
  resetPswApi,
  selectUserLabApi
} from "@/api/modules/experimentalist/index";
import { selectLaboratoryApi } from "@/api/modules/laboratory/index";
import { ExperimentaListType, QueryParamType, addEditFormDataType } from "@/api/modules/experimentalist/type";
import { ElMessage } from "element-plus";

const addEditCurrentNodeKey = ref("");

// 添加/编辑实验员当前步骤
const currentAddEditStep = ref(0);

// 添加/编辑实验员弹窗上一步点击事件
const addEditDialogBackStepClick = () => {
  currentAddEditStep.value = 0;
  stepsList.value[0].description = "正在进行";
  stepsList.value[1].description = "";
};

// 添加/编辑实验员 步骤数据
const stepsList = ref([
  {
    title: "填写实验员信息",
    description: ""
  },
  {
    title: "选择归属实验室",
    description: ""
  }
]);

//添加/修改表单数据
const addEditFormData = ref<addEditFormDataType>({
  id: null,
  account: "",
  name: "",
  age: null,
  email: "",
  isManager: ""
});

// 添加/编辑表单Ref
const addEditFormRef = ref<any>(null);

// 添加/编辑表单校验规则
const addEditFormRule = ref({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  account: [{ required: true, message: "请输入用户名", trigger: "blur" }]
});

// 添加/编辑实验室归属id数组
const addEditLabIdList = ref([]);

// 添加/编辑实验员-实验室Tree组件Ref
const addEditExpLabTreeRef = ref("");

// 选择数组C
// const selectLabIdsC = ref([]);

// 取消选择数组
const cancelSelectLabIdsC = ref([]);

// 添加/编辑实验员树形结构CheckChange事件
const addEditTreeCheckChange = e => {
  console.log(e);
  // 上级节点Node
  let prNode = addEditExpLabTreeRef.value.getNode(e).parent.data;
  // 上级节点id
  let prNodeId = prNode.id;
  console.log("prNode", prNode);
  // 选中的节点数组
  let checkLabNodeArr = addEditExpLabTreeRef.value.getCheckedNodes();
  // 选择之前查询的实验室id数组
  let selectOldLabIdList = JSON.parse(JSON.stringify(addEditLabIdListC.value));
  // 取消选择的节点数组
  let cancelSelectNodeArr = [];

  // 选中的id数组
  let checkLabNodeIdArr = checkLabNodeArr.map(item => {
    let cId = item.id;
    return cId;
  });

  // 半选节点数组
  let halfCheckedKeys = addEditExpLabTreeRef.value.getHalfCheckedKeys();

  let nselectIds = JSON.parse(JSON.stringify(checkLabNodeIdArr));

  selectOldLabIdList.forEach(item => {
    console.log(item);
    if (checkLabNodeIdArr.indexOf(item) == -1) {
      cancelSelectNodeArr.push(item);

      // console.log(checkLabNodeArr)
      // console.log("没找到");
    }
  });

  // 判断选中数组当中是否存在半选，如果没有就添加
  // halfCheckedKeys.forEach(hafl => {
  //   if (nselectIds.indexOf(hafl) == -1) {
  //     nselectIds.push(hafl);
  //   }
  // });
  console.log("半选节点数组", halfCheckedKeys);
  console.log("选中数组", checkLabNodeIdArr);
  console.log("之前选中数组", selectOldLabIdList);
  // console.log("提交选择数组", nselectIds);
  console.log("取消选择数组", cancelSelectNodeArr);
  addEditLabIdList.value = checkLabNodeIdArr;
  // selectLabIdsC.value = nselectIds;
  cancelSelectLabIdsC.value = cancelSelectNodeArr;
};

// 添加/编辑表单确定点击事件
const addEditDialogConfirmClick = async formRef => {
  if (!formRef) return;
  await formRef.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      if (currentAddEditStep.value == 0) {
        currentAddEditStep.value = 1;
        stepsList.value[0].description = "已完成";
        stepsList.value[1].description = "正在进行";
      } else if (currentAddEditStep.value == 1) {
        // 判断是添加还是修改，走不同的请求路线
        if (isFormAdd.value) {
          let data = {
            account: addEditFormData.value.account,
            name: addEditFormData.value.name,
            age: addEditFormData.value.age,
            email: addEditFormData.value.email,
            isManager: addEditFormData.value.isManager,
            selectLabList: addEditLabIdList.value.join(";")
          };

          console.log("添加提交数据", data);

          addLabUserFunc(data);
        } else {
          let selectLabListQ = addEditLabIdList.value.join(";");
          let cancelLabListQ = cancelSelectLabIdsC.value.join(";");
          console.log("选择的ids", selectLabListQ);
          console.log("取消的ids", cancelLabListQ);
          let data = {
            id: addEditFormData.value.id,
            account: addEditFormData.value.account,
            name: addEditFormData.value.name,
            age: addEditFormData.value.age,
            email: addEditFormData.value.email,
            isManager: addEditFormData.value.isManager,
            selectLabList: selectLabListQ,
            cancelLabList: cancelLabListQ
            //
          };

          console.log("修改提交数据", data);
          editLabUserFunc(data);

          isShowAddEditDialog.value = false;
          formRef.resetFields();
        }
      } else {
        console.log("error submit!", fields);
      }
    }
  });
};

// 添加实验员请求函数
const addLabUserFunc = async (data: addEditFormDataType) => {
  await addLabUserApi(data)
    .then(res => {
      if (res.status == 400) {
        ElMessage.error(res.msg);
      } else {
        ElMessage.success("添加成功");
        addEditLabIdList.value = [];
        isShowAddEditDialog.value = false;
      }
    })
    .catch(err => {
      ElMessage.error("添加失败");
    })
    .finally(() => {
      selectExperimentalistListFunc();
    });
};
// 编辑实验员请求函数
const editLabUserFunc = async (data: addEditFormDataType) => {
  await editLabUserApi(data)
    .then(res => {
      ElMessage.success("编辑成功");
      addEditLabIdList.value = [];
      isShowAddEditDialog.value = false;
    })
    .catch(err => {
      ElMessage.error("编辑失败");
    })
    .finally(() => {
      selectExperimentalistListFunc();
    });
};

// 删除实验员确定点击事件
const delLabUserConfirmClick = async row => {
  await delLabUserApi({
    tbLabUserId: row.id
  })
    .then(res => {
      // ElMessage.success("删除成功");
    })
    .catch(err => {
      ElMessage.error("删除失败");
    })
    .finally(() => {
      selectExperimentalistListFunc();
    });
};

// 重置密码确定点击事件
const resetPswConfirmClick = async row => {
  await resetPswApi({
    tbLabUserId: row.id
  })
    .then(res => {
      ElMessage.success("重置成功");
    })
    .catch(err => {
      ElMessage.error("重置失败");
    })
    .finally(() => {
      selectExperimentalistListFunc();
    });
};

// 添加/编辑表单取消点击事件
const addEditDialogCancelClick = () => {
  isShowAddEditDialog.value = false;
  resetAddEditFormData();
  addEditLabIdList.value = [];
  addEditFormRef.value.resetFields();
};

// 重置添加/编辑表单数据
const resetAddEditFormData = () => {
  addEditFormData.value = {
    id: null,
    account: "",
    name: "",
    age: 0,
    email: "",
    isManager: ""
  };
};

// 显示添加/编辑弹窗的标识
const isShowAddEditDialog = ref(false);

// 当前弹窗是添加还是修改的标识
const isFormAdd = ref(false);

// 加载标识
const isLoading = ref(false);

// 总数据条数
const total = ref(0);

// 添加/编辑点击事件
const addEditClick = (type, row) => {
  addEditLabIdList.value = [];
  currentAddEditStep.value = 0;
  stepsList.value[0].description = "正在进行";
  stepsList.value[1].description = "";

  isShowAddEditDialog.value = true;
  type == 1 ? (isFormAdd.value = false) : (isFormAdd.value = true);

  // 显示弹窗
  // 如果是编辑，就将那项的内容赋值给表单
  if (type == 1) {
    if (row) {
      selectUserLabFunc(row);
      addEditFormData.value.id = row.id;
      addEditFormData.value.account = row.account;
      addEditFormData.value.name = row.name;
      addEditFormData.value.email = row.email;
      addEditFormData.value.age = row.age;
      addEditFormData.value.isManager = row.isManager;
    }
  }
};

// 查询点击事件
const querySelectClick = () => {
  queryParamData.value.page = 1;
  selectExperimentalistListFunc();
};

// 页码change事件
const pageChange = e => {
  queryParamData.value.page = e;
  selectExperimentalistListFunc();
};

// 最大条数change事件
const sizeChange = e => {
  queryParamData.value.size = e;
  selectExperimentalistListFunc();
};

// 实验员列表数据
let experimentaList = ref<ExperimentaListType | []>([]);

// 查询参数数据
const queryParamData = ref<QueryParamType>({
  account: "",
  name: "",
  isManager: "",
  page: 1,
  size: 15
});

// 分页表格数据
const byPageTableData = ref<ExperimentaListType | []>([]);

// 分页取数据函数
const byPagePullDataFunc = () => {
  // 分页信息
  let byPageInfo = {
    page: queryParamData.value.page,
    size: 15,
    account: queryParamData.value.account,
    name: queryParamData.value.name,
    isManager: queryParamData.value.isManager
  };

  // 原数据
  let expAllData = experimentaList.value;

  // 赋值总数
  total.value = experimentaList.value.length;

  // 过滤
  let tableFilterData = expAllData
    .filter(item => {
      let flag = false;
      if (byPageInfo.account == "" || byPageInfo.account == null || byPageInfo.account == undefined) {
        flag = true;
      } else {
        flag = item.account.indexOf(byPageInfo.account) != -1;
      }
      return flag;
    })
    .filter(item => {
      let flag = false;
      if (byPageInfo.name == "" || byPageInfo.name == null || byPageInfo.name == undefined) {
        flag = true;
      } else {
        flag = item.name.indexOf(byPageInfo.name) != -1;
      }
      return flag;
    })
    .filter(item => {
      let flag = false;
      if (byPageInfo.isManager == "" || byPageInfo.isManager == null || byPageInfo.isManager == undefined) {
        flag = true;
      } else {
        flag = item.isManager.indexOf(byPageInfo.isManager) != -1;
      }
      return flag;
    });

  total.value = tableFilterData.length;

  // 开始分页截取index
  let pageStartIndex = (byPageInfo.page - 1) * byPageInfo.size;
  // 结束分页截取index
  let pageEndIndex = byPageInfo.page * byPageInfo.size;

  // 最终分页数据截取
  let rData = tableFilterData.slice(pageStartIndex, pageEndIndex);
  rData.forEach((item, exIndex) => {
    item.serialNumber = (queryParamData.value.page - 1) * queryParamData.value.size + (exIndex + 1);
  });

  byPageTableData.value = rData;
};

// 查询实验员的函数
const selectExperimentalistListFunc = async () => {
  isLoading.value = true;
  // queryParamData.value.page = 1;
  await selectExperimentalistListApi(queryParamData.value)
    .then(res => {
      experimentaList.value = res.data;
      // console.log("实验员数量", res.data.length);
      // total.value = res.data.length;
      byPagePullDataFunc();
    })
    .finally(() => {
      isLoading.value = false;
    });
};

// 实验室结构数据
const dataSource = ref<laboratoryListType>();

// 处理实验室结构数据的函数
const disposeLaboratoryDataFunc = (data: laboratoryListType) => {
  let nData = [];
  // 处理数据
  data.children = data.tbTabRspList;
  data.label = data.address;
  data.disabled = 0;
  delete data.tbTabRspList;

  // 判断是否存在子数据，进行递归遍历
  if (data.children && data.children.length != 0) {
    data.children.forEach((item: laboratoryListType) => {
      disposeLaboratoryDataFunc(item);
    });
  }
};

// 添加层级标识的函数
const addTierTagFunc = () => {
  dataSource.value?.forEach(item1 => {
    item1.tags = 1;
    if (item1.children?.length != 0) {
      item1.children.forEach(item2 => {
        item2.tags = 2;
        if (item2.children?.length != 0) {
          item2.children.forEach(item3 => {
            item3.tags = 3;
            if (item3.children?.length != 0) {
              item3.children.forEach(item4 => {
                item4.tags = 4;
              });
            }
          });
        }
      });
    }
  });
};

// 查询实验室结构的函数
const selectLaboratoryFunc = async () => {
  await selectLaboratoryApi().then(res => {
    console.log(res.data);
    res.data.forEach((item: laboratoryListType) => {
      disposeLaboratoryDataFunc(item);
    });

    dataSource.value = res.data;
    addTierTagFunc();
  });
};

// 实验室选中的实验室id列表C
const addEditLabIdListC = ref([]);

// 根据实验员id查询实验室列表的函数
const selectUserLabFunc = async item => {
  await selectUserLabApi({
    selectUserId: item.id
  }).then(res => {
    let selectLabIdList = [];
    let sllData = res.data;
    // 遍历第一层
    sllData.forEach(item1 => {
      // 判断第一层权限
      if (item1.isSelect == 1) {
        selectLabIdList.push(item1.id);
      }
      if (item1.tbTabRspList || item1.tbTabRspList.length == 0) {
        // 遍历第二层
        item1.tbTabRspList.forEach(item2 => {
          // 判断第二层权限
          if (item2.isSelect == 1) {
            selectLabIdList.push(item2.id);
          }
          if (item2.tbTabRspList || item2.tbTabRspList.length == 0) {
            // 遍历第三层
            item2.tbTabRspList.forEach(item3 => {
              // 判断第三层权限
              if (item3.isSelect == 1) {
                selectLabIdList.push(item3.id);
              }

              if (item3.tbTabRspList || item3.tbTabRspList.length == 0) {
                // 遍历第四层
                item3.tbTabRspList.forEach(item4 => {
                  // 判断第四层权限
                  if (item4.isSelect == 1) {
                    selectLabIdList.push(item4.id);
                  }
                });
              }
            });
          }
        });
      }
    });
    console.log("所有选中的id", selectLabIdList);
    addEditLabIdList.value = selectLabIdList;
    addEditLabIdListC.value = JSON.parse(JSON.stringify(selectLabIdList));
  });
};

onMounted(() => {
  selectExperimentalistListFunc();
  selectLaboratoryFunc();
});
</script>

<style lang="scss" scoped>
.experimentalist_wrap {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  .experimentalist_top_box {
    width: 100%;
    height: 70px;
    .experimentalist_top_card {
      width: 100%;
      height: 100%;
    }
  }
  .experimentalist_bottom_box {
    flex: 1;
    width: 100%;
    margin-top: 14px;
    .experimentalist_bottom_card {
      width: 100%;
      height: 100%;
    }
  }
  .pagination_box {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }
  .add_edit_form_box {
    padding: 40px 40px 0 20px;
  }
  .operation_box {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 0 12px;
    .edit_text {
      color: blue;
      cursor: pointer;
    }
    .del_text {
      color: red;
      cursor: pointer;
    }
  }
  .pws_zs {
    padding-left: 40px;
    margin-top: 40px;
    color: rgb(207 8 8);
    text-align: center;
    .label {
      font-size: 12px;
      letter-spacing: 1px;
    }
    .pws_zs_text {
      font-size: 12px;
      letter-spacing: 1px;
    }
  }
}
:deep(.experimentalist_bottom_card .el-card__body) {
  padding: 14px;
}
:deep(.el-timeline) {
  display: flex;
  flex-direction: row;
}
.processBox {
  position: relative;
  left: 50%;
  width: 400px;
  padding-top: 20px;
  transform: translateX(-50%);
}
.hids {
  z-index: -20 !important;
  display: none !important;
  opacity: 0;
}
.add_edit_tree_box {
  position: relative;
  left: 50%;
  width: 400px;
  height: 400px;
  overflow-y: auto;
  padding: 20px 20px;
  margin-top: 30px;
  margin-bottom: 30px;
  transform: translateX(-50%);
}

.is_m_box {
  padding-left: 70px;

  .label {
    margin-right: 20px;
    position: relative;
    top: -2px;
  }
}

:deep(.is-indeterminate) {
  .el-checkbox__inner {
    background: transparent;
    border-color: #dcdfe6;
  }
  // background: transparent;
}
</style>
